import { defineStore } from 'pinia';
import {
  login as userLogin,
  logout as userLogout,
  getUserInfo,
  LoginData,
} from '@/api/user';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { UserState } from './types';
import useAppStore from '../app';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    name: undefined,
    avatar: undefined,
    job: undefined,
    organization: undefined,
    location: undefined,
    email: undefined,
    introduction: undefined,
    personalWebsite: undefined,
    jobName: undefined,
    organizationName: undefined,
    locationName: undefined,
    phone: undefined,
    registrationDate: undefined,
    accountId: undefined,
    certification: undefined,
    isAdmin: 0,
    role: '',
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.role = this.role === 'user' ? 'admin' : 'user';
        resolve(this.role);
      });
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async info() {
      try {
        console.log('获取用户信息...');
        const res = await getUserInfo();
        console.log('用户信息响应:', res);
        
        // 处理后端响应
        let userData = null;
        
        if (res.data) {
          // 如果后端返回的是标准格式 { code: 200, data: {...}, msg: 'success' }
          if (res.data.code === 200 && res.data.data) {
            userData = res.data.data;
          } else {
            userData = res.data;
          }
          
          // 设置用户信息
          this.setInfo({
            name: userData.nickName || userData.username || userData.name,
            avatar: userData.avatar,
            accountId: String(userData.id || ''),
            email: userData.email,
            phone: userData.mobile || userData.phone,
            role: userData.isAdmin === 1 ? 'admin' : 'user',
            isAdmin: userData.isAdmin
          });
        }
        
        return userData;
      } catch (error) {
        console.error('获取用户信息失败:', error);
        return null;
      }
    },

    // Login
    async login(loginForm: LoginData) {
      try {
        console.log('登录请求数据:', loginForm);
        const res = await userLogin(loginForm);
        console.log('登录响应:', res);
        
        // 处理不同的响应格式
        let token = '';
        
        // 检查响应格式
        if (res.data) {
          // 格式1: { code: 200, data: { token: 'xxx' }, msg: 'success' }
          if (res.data.code === 200 && res.data.data && res.data.data.token) {
            token = res.data.data.token;
          }
          // 格式2: { code: 200, data: 'token-string', msg: 'success' }
          else if (res.data.code === 200 && typeof res.data.data === 'string') {
            token = res.data.data;
          }
          // 格式3: { token: 'xxx' }
          else if (res.data.token) {
            token = res.data.token;
          }
          // 格式4: 'token-string'
          else if (typeof res.data === 'string') {
            token = res.data;
          }
        }
        
        if (!token) {
          console.error('无法从响应中获取token:', res);
          throw new Error('登录失败：无法获取访问令牌');
        }
        
        // 保存token
        setToken(token);
        
        // 获取用户信息
        await this.info();
        
        // 获取应用配置
        const appStore = useAppStore();
        if (typeof appStore.fetchServerMenuConfig === 'function') {
          console.log('开始获取菜单数据...');
          appStore.fetchServerMenuConfig();
        }
        
        return true;
      } catch (error) {
        console.error('登录失败:', error);
        throw error;
      }
    },
    
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      try {
        await userLogout();
      } catch (error) {
        console.error('登出失败:', error);
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
